package com.och.mrcp.core.sip.model;

import lombok.Data;
import java.util.HashMap;
import java.util.Map;

@Data
public class SipUri {
    
    private String scheme = "sip";
    private String user;
    private String password;
    private String host;
    private int port = 5060;
    private Map<String, String> parameters = new HashMap<>();
    private Map<String, String> headers = new HashMap<>();
    
    public SipUri() {}
    
    public SipUri(String host) {
        this.host = host;
    }
    
    public SipUri(String user, String host) {
        this.user = user;
        this.host = host;
    }
    
    public SipUri(String user, String host, int port) {
        this.user = user;
        this.host = host;
        this.port = port;
    }
    
    public void addParameter(String name, String value) {
        parameters.put(name, value);
    }
    
    public String getParameter(String name) {
        return parameters.get(name);
    }
    
    public void addHeader(String name, String value) {
        headers.put(name, value);
    }
    
    public String getHeader(String name) {
        return headers.get(name);
    }
    
    public static SipUri parse(String uriString) {
        SipUri uri = new SipUri();
        
        try {
            // 移除sip:前缀
            if (uriString.startsWith("sip:")) {
                uriString = uriString.substring(4);
            }
            
            // 解析用户信息
            int atIndex = uriString.indexOf('@');
            if (atIndex > 0) {
                String userPart = uriString.substring(0, atIndex);
                int colonIndex = userPart.indexOf(':');
                if (colonIndex > 0) {
                    uri.setUser(userPart.substring(0, colonIndex));
                    uri.setPassword(userPart.substring(colonIndex + 1));
                } else {
                    uri.setUser(userPart);
                }
                uriString = uriString.substring(atIndex + 1);
            }
            
            // 解析主机和端口
            int colonIndex = uriString.indexOf(':');
            int semicolonIndex = uriString.indexOf(';');
            int questionIndex = uriString.indexOf('?');
            
            int endIndex = uriString.length();
            if (semicolonIndex > 0 && semicolonIndex < endIndex) {
                endIndex = semicolonIndex;
            }
            if (questionIndex > 0 && questionIndex < endIndex) {
                endIndex = questionIndex;
            }
            
            String hostPort = uriString.substring(0, endIndex);
            if (colonIndex > 0 && colonIndex < endIndex) {
                uri.setHost(hostPort.substring(0, colonIndex));
                uri.setPort(Integer.parseInt(hostPort.substring(colonIndex + 1)));
            } else {
                uri.setHost(hostPort);
            }
            
            // 解析参数
            if (semicolonIndex > 0) {
                String paramString = uriString.substring(semicolonIndex + 1);
                if (questionIndex > 0) {
                    paramString = uriString.substring(semicolonIndex + 1, questionIndex);
                }
                parseParameters(uri, paramString);
            }
            
            // 解析头部
            if (questionIndex > 0) {
                String headerString = uriString.substring(questionIndex + 1);
                parseHeaders(uri, headerString);
            }
            
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid SIP URI: " + uriString, e);
        }
        
        return uri;
    }
    
    private static void parseParameters(SipUri uri, String paramString) {
        String[] params = paramString.split(";");
        for (String param : params) {
            int equalIndex = param.indexOf('=');
            if (equalIndex > 0) {
                String name = param.substring(0, equalIndex);
                String value = param.substring(equalIndex + 1);
                uri.addParameter(name, value);
            }
        }
    }
    
    private static void parseHeaders(SipUri uri, String headerString) {
        String[] headers = headerString.split("&");
        for (String header : headers) {
            int equalIndex = header.indexOf('=');
            if (equalIndex > 0) {
                String name = header.substring(0, equalIndex);
                String value = header.substring(equalIndex + 1);
                uri.addHeader(name, value);
            }
        }
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(scheme).append(":");
        
        if (user != null) {
            sb.append(user);
            if (password != null) {
                sb.append(":").append(password);
            }
            sb.append("@");
        }
        
        sb.append(host);
        if (port != 5060) {
            sb.append(":").append(port);
        }
        
        // 添加参数
        if (!parameters.isEmpty()) {
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                sb.append(";").append(entry.getKey());
                if (entry.getValue() != null) {
                    sb.append("=").append(entry.getValue());
                }
            }
        }
        
        // 添加头部
        if (!headers.isEmpty()) {
            sb.append("?");
            boolean first = true;
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                if (!first) {
                    sb.append("&");
                }
                sb.append(entry.getKey());
                if (entry.getValue() != null) {
                    sb.append("=").append(entry.getValue());
                }
                first = false;
            }
        }
        
        return sb.toString();
    }
}
